/**
 * Copyright (c) 2023 - present All rights reserved.
 * <p>
 * Reprinted has been protected by the copyright laws.
 */

package cn.myxl.smart.devkit.commit.submission;

import cn.myxl.smart.devkit.commit.model.CommitTemplate;
import cn.myxl.smart.devkit.commit.model.CommitType;
import cn.myxl.smart.devkit.commit.model.SettingState;
import cn.myxl.smart.devkit.core.util.VelocityUtils;
import org.apache.commons.lang.StringUtils;

/**
 * @author zhangyang
 * @date 2023-11-14 16:24
 */

public class CommitMessage {
	private static final int MAX_LINE_LENGTH = 72; // https://stackoverflow.com/a/2120040/5138796
	private final String content;

	public CommitMessage(
			SettingState settings, CommitType typeAlias, String changeScope, String shortDescription,
			String longDescription, String closedIssues, String breakingChanges) {

		this.content = buildContent(settings, typeAlias, changeScope, shortDescription, longDescription, breakingChanges, closedIssues);
	}

	private String buildContent(
			SettingState settings, CommitType typeAlias, String changeScope, String shortDescription,
			String longDescription, String breakingChanges, String closedIssues) {

		CommitTemplate commitTemplate = new CommitTemplate();

		if (typeAlias != null) {
			if (StringUtils.isNotBlank(typeAlias.getTitle())) {
				commitTemplate.setType(typeAlias.getTitle());
			}
		}

		if (StringUtils.isNotBlank(changeScope)) {
			commitTemplate.setScope(changeScope);
		}

		if (StringUtils.isNotBlank(shortDescription)) {
			commitTemplate.setSubject(shortDescription);
		}

		if (StringUtils.isNotBlank(longDescription)) {
			commitTemplate.setBody(longDescription);
		}

		if (StringUtils.isNotBlank(breakingChanges)) {
			commitTemplate.setChanges(breakingChanges);
		}

		if (StringUtils.isNotBlank(closedIssues)) {
			commitTemplate.setCloses(closedIssues);
		}

		String template = settings.getTemplate();

		return VelocityUtils.convert(template, commitTemplate);
	}

	@Override
	public String toString() {
		return content;
	}
}
